#  This is part of Scopia Visual Framework
#
#  Copyright (C) 2008  Scopia Visual Interfaces Systems 
#                      http://www.scopia.es
#
#  author: Alejandro Conty
#  contributors:
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
from OpenGL.GLUT import *
from OpenGL.GL import glViewport
import sys
import time
from scopiavf.adaptors import adaptor_t

class glutAdaptor_t(adaptor_t):

    def __init__(self, w, h, appfunc):
        adaptor_t.__init__(self)
        glutInit( sys.argv )
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowSize( w, h )
        glutInitWindowPosition(0, 0)
        self.width, self.height = w, h
        window = glutCreateWindow("context GL")
        
        self.app = appfunc(w, h)
        self.app.width, self.app.height = self.width, self.height
        self.app.forceDisplay = glutPostRedisplay

        glutDisplayFunc( self.display )
        glutReshapeFunc( self.resize )
        glutKeyboardFunc( self.keyboard )
        glutMouseFunc( self.mouse )
        glutMotionFunc( self.motion )
        glutPassiveMotionFunc( self.passiveMotion )
        glutTimerFunc( 10, self.timer, 0 )

    def display(self):
        #self.countFrames()
        self.app._display()
        glutSwapBuffers()
    
    def resize(self, w, h):
        self.app.width = self.width = w
        self.app.height = self.height = h
        glViewport(0, 0, w, h)
    
    def keyboard( self, key, x, y ): self.app.keyboard( key, x, y )
    
    def mouse( self, button, state, x, y):
        if button == GLUT_LEFT_BUTTON:     b = (True,  False, False, False, False)
        elif button == GLUT_RIGHT_BUTTON:  b = (False, False, True, False, False)
        elif button == GLUT_MIDDLE_BUTTON: b = (False, True,  False, False, False)
        elif button == 3: b = (False, False,  False, True, False)
        elif button == 4: b = (False, False,  False, False, True)
        else: b = (False, False, False, False, False)
        down = state == GLUT_DOWN
        self.app.mouse( b, down, x, y)
    
    def motion( self, x, y): self.app.motion(x, y)
    def passiveMotion( self, x, y): self.app.passiveMotion(x, y)

    def loop(self):
        glutMainLoop()

    def timer( self, nada ):
        self.app.timer()
        glutTimerFunc( 10, self.timer, 0 )
        
